package br.com.petsis.conversores;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import br.com.petsis.utilitarios.UtilString;

public class ConversorTelefone implements Converter {

    public Object getAsObject(FacesContext context, UIComponent component, String valorCampo){
	   Object telefone = null;
	   if(valorCampo != null) {
           if(!UtilString.isStringVazia(valorCampo)){
        	   telefone = desmascara(valorCampo);
           }
	   }
	   return telefone;
    }

    public String getAsString(FacesContext context, UIComponent component, Object objCampo){
       String telefone = null;
       if(objCampo != null) {
           if(!UtilString.isStringVazia(objCampo.toString())){
        	   telefone = mascara(objCampo);
           }
       }
       return telefone;
    }
    
    public static Object desmascara(String telefone) {
    	telefone = UtilString.removeAll('(', telefone);
    	telefone = UtilString.removeAll(')', telefone);
    	telefone = UtilString.removeAll(' ', telefone);
    	return telefone;
    }

    public static String mascara(Object telefone) {
    	StringBuffer stringBuffer = new StringBuffer(telefone.toString());
    	stringBuffer.insert(0, "("); 
    	stringBuffer.insert(3, ")");
    	stringBuffer.insert(4, " ");
    	return stringBuffer.toString();
    }

}
